import { Component, Inject } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ITokenService, DA_SERVICE_TOKEN } from '@delon/auth';
import { environment } from '@env/environment';
import { MenuService } from '@delon/theme';

@Component({
    selector: 'passport-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.less']
})
export class UserLoginComponent {

    form: FormGroup;
    error = '';
    type = 0;
    loading = false;

    constructor(
        fb: FormBuilder,
        private router: Router,
        private menuService: MenuService,
        private httpClient: HttpClient,
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService) {
        this.form = fb.group({
            userName: [null, [Validators.required, Validators.minLength(5)]],
            password: [null, Validators.required],
            remember: [true]
        });
    }

    // region: fields

    get userName() { return this.form.controls.userName; }
    get password() { return this.form.controls.password; }

    // endregion


    submit() {
        this.error = '';
        this.userName.markAsDirty();
        this.password.markAsDirty();
        if (this.userName.invalid || this.password.invalid) return;

        this.loading = true;
        //const body = { username: this.userName.value, password: this.password.value };
        const body = 'username=' + this.userName.value + '&password=' + this.password.value;
        this.httpClient.post('api/sys/user/login', body, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).subscribe((res: any) => {
            this.loading = false;

            if (res.code != 0) {
                this.error = res.message;
            } else {
                this.tokenService.set({
                    token: res.data,
                    name: this.userName.value
                });

                this.httpClient.get('api/sys/menu/list')
                .subscribe((res: any) => {
                    // 初始化菜单
                    this.menuService.clear();
                    localStorage.setItem("menu",JSON.stringify(res.data));
                    this.menuService.add(res.data);
                    this.router.navigate(['/']);
                });
                
               // this.router.navigate(['/']);
            }
        }, (err: HttpErrorResponse) => {
            console.log(err);
        });
    }




}
